package org.dreamwork.android.websocket.impls.async_http_client_1_9_40;

import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.ws.WebSocket;
import com.ning.http.client.ws.WebSocketUpgradeHandler;
import org.dreamwork.android.websocket.IWebSocketLibrary;
import org.dreamwork.android.websocket.IWebSocketListener;

/**
 * Created by game on 2017/3/6
 */
public final class AsyncHttpClientLibrary implements IWebSocketLibrary {
    private WebSocket          socket   = null;
    private AsyncHttpClient    client   = null;
    private IWebSocketListener listener = null;

    public AsyncHttpClientLibrary (IWebSocketListener listener) {
        this.listener = listener;
    }

    @Override
    public void connect (String url) throws Exception {
        client = new AsyncHttpClient ();
        WebSocketUpgradeHandler.Builder builder = new WebSocketUpgradeHandler.Builder ();
        builder.addWebSocketListener (new AsyncHttpClientWebSocketListenerDelegate (listener));
        AsyncHandler<WebSocket> handler = builder.build ();
        socket = client.prepareGet (url).execute (handler).get ();
    }

    @Override
    public void send (String message) {
        socket.sendMessage (message);
    }

    @Override
    public void send (byte[] message) {
        socket.sendMessage (message);
    }

    @Override
    public void close () {
        if (socket != null) socket.close ();
        if (client != null) client.close ();
    }
}
